import axios from "axios";
import { getToken,removeToken } from '@/utils/token';
import { ElMessage } from 'element-plus';

// 实例化一个axios对象request
const request = axios.create({
  baseURL: "https://apifoxmock.com/m1/5275854-4944423-default/",
  timeout: 5000,
});

// post请求
export const post = (obj) => {
  obj.method = "POST";
  return request(obj);
};

// get请求
export const get = (obj) => {
  obj.method = "GET";
  if (obj.data) {
    obj.url +=
      "?" +
      Object.keys(obj.data)
        .map((key) => key + "=" + obj.data[key])
        .join("&");
        // http://localhost:3000/api/user?username=admin&password=123456
  }
  return request(obj);
};

// 请求拦截
request.interceptors.request.use(function (config) {
  const token = getToken()
  if (token) {
      config.headers['token'] = token
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 响应拦截
request.interceptors.response.use(
  response => {
    return response.data;
  },
  error =>  {
    if(error.response && error.response.status == 401){
      ElMessage({
        message: '登录失效，请重新登录',
        type: 'error',
      })
      removeToken()
      window.location.reload()
    }
    else{
      ElMessage({
          message: '请求异常，请检查服务器状态',
          type: 'error',
      })
    }
    return Promise.reject(error)
  });
